import { test } from '@jest/globals';
import { iconv } from '@ohos/hvigor';
import assert from 'assert';

const testString = '中国abc';
const testStringGBKBuffer = Buffer.from([0xd6, 0xd0, 0xb9, 0xfa, 0x61, 0x62, 0x63]);
describe('GBK tests', function () {
  test.concurrent('can encode/decode string', async () => {
    const buf = iconv.encode(testString, 'GBK');
    const str = iconv.decode(buf, 'GBK');
    assert.equal(str, testString);
  });

  test.concurrent('GBK correctly encoded/decoded', async () => {
    assert.strictEqual(iconv.encode(testString, 'GBK').toString('binary'), testStringGBKBuffer.toString('binary'));
    assert.strictEqual(iconv.decode(testStringGBKBuffer, 'GBK'), testString);
  });

  test.concurrent('GBK correctly decodes and encodes characters · and ×', async () => {
    const chars = '·×';
    const gbkChars = Buffer.from([0xA1, 0xA4, 0xA1, 0xC1]);
    assert.strictEqual(iconv.encode(chars, 'GBK').toString('binary'), gbkChars.toString('binary'));
    assert.strictEqual(iconv.decode(gbkChars, 'GBK'), chars);
  });

  test.concurrent('GBK correctly decodes and encodes Euro character', async () => {
    const gbkEuroEncoding1 = Buffer.from([0x80]),
      gbkEuroEncoding2 = Buffer.from([0xA2, 0xE3]),
      strEuro = '€';

    assert.strictEqual(iconv.decode(gbkEuroEncoding1, 'GBK'), strEuro);
    assert.strictEqual(iconv.decode(gbkEuroEncoding2, 'GBK'), strEuro);
    assert.strictEqual(iconv.encode(strEuro, 'GBK').toString('hex'), gbkEuroEncoding1.toString('hex'));
  });

  test.concurrent('handles Object & Array prototypes monkey patching', async () => {
    // eslint-disable-next-line no-extend-native
    Object.defineProperty(Object.prototype, 'permits', {
      value: () => {
        // nothing
      },
      writable: true,
      enumerable: true,
      configurable: true,
    });
    // eslint-disable-next-line no-extend-native
    Object.defineProperty(Array.prototype, 'sample2', {
      value: () => {
        // nothing
      },
      writable: true,
      enumerable: true,
      configurable: true,
    });

    assert.strictEqual(iconv.decode(Buffer.from('abc'), 'gbk'), 'abc');
    assert.strictEqual(iconv.encode('abc', 'gbk').toString(), 'abc');
  });
});
